package com.eternal.widget;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.inputmethodservice.InputMethodService;
import android.util.AttributeSet;
import android.widget.Switch;

import com.eternal.framework.utils.KLog;

public class SwitchButton extends Switch {
    private LayerDrawable thumb;
    private StateListDrawable track;
    private boolean resize;

    public SwitchButton(Context context) {
        super(context);
        init();
    }

    public SwitchButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SwitchButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
//        thumb= (LayerDrawable) getResources().getDrawable(R.drawable.litter_switch_circle);
//        track= (StateListDrawable) getResources().getDrawable(R.drawable.litter_switch_background);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        KLog.e("width:" + w + " height:" + h);
        if (!resize) {
            int size= (int) (Math.min(w/2, getMeasuredHeight())*0.8);
            changeThumb((LayerDrawable) getThumbDrawable(), size);
            changeTick((StateListDrawable) getTrackDrawable(), w, size);
//            setThumbDrawable(thumb);
//            setTrackDrawable(track);
            resize=true;
            postInvalidate();
        }
    }

    private void changeThumb(LayerDrawable layer, int size) {
        GradientDrawable thumb = (GradientDrawable) layer.getDrawable(0);
//        layer.setLayerInset(0, 5, 5, 5, 5);
        thumb.setSize(size, size);
        KLog.e(String.format("thumb width:%d height:%d size:%d", layer.getIntrinsicWidth(), layer.getIntrinsicHeight(), size));
    }

    private void changeTick(StateListDrawable tick, int width, int size) {
        DrawableContainer.DrawableContainerState state = (DrawableContainer.DrawableContainerState) tick.getConstantState();
        if (state == null) {
            return;
        }
        GradientDrawable track;
        for (int i = 0; i < state.getChildCount(); i++) {
            track = (GradientDrawable) state.getChild(i);
            track.setSize(width, size);
        }
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
